<script setup lang="ts">
definePageMeta({
  // 禁用布局
  layout: false,
});

import { removeItem } from "~/utils/arr";
import type { FormInstance } from "element-plus";

const appConfig = useAppConfig();
const callbackMessage = useCallbackMessage();

let accountList: string[] = reactive([]);
const formData = reactive({ account: "", password: "", remember: false });
const ref_form = ref<FormInstance>();
const currentUserStore = useCurrentUserStore();
const permissionStore = usePermissionStore();

onMounted(() => {
  let accountList_str = localStorage.getItem("accountList");
  if (accountList_str) {
    accountList = JSON.parse(accountList_str);
  }
});

const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        const result = await $fetch("/api/user/login", {
          body: formData,
          method: "POST",
        });
        callbackMessage.value = {
          show: true,
          valid: true,
          content: "登录成功，即将跳转到首页",
        };

        // 记录登录日志
        useLog("登录", result.account, result.name);

        // 根据是否勾选记住账号，更新本地存储的账号列表
        let account = formData.account;
        // 勾选-记住账号
        if (formData.remember) {
          // 没记住过
          if (!accountList.includes(account)) {
            accountList.push(account);
          }
        } else {
          // 未勾选-记住账号
          removeItem(accountList, account);
        }
        localStorage.setItem("accountList", JSON.stringify(accountList));

        // 账号为 admin ，则为超级管理员
        let ifSuperAdmin = result.account === "admin";
        // 从角色列表中查询出所有权限
        let fetch_list = result.roles.map((roleID) =>
          $fetch(`/api/role/${roleID}`)
        );
        const { data } = await useAsyncData("permissionList", async () => {
          const res_List = await Promise.all(fetch_list);

          // 用 Set 去重
          let menu_permissionSet = new Set();
          let handle_permissionSet = new Set();

          res_List.forEach((item: any) => {
            // 角色含有超级管理员 ，则为超级管理员
            if (item.name === "超级管理员") {
              ifSuperAdmin = true;
            }
            // 菜单权限
            let menu_permissionList_item = item.permissionDic.menu;
            menu_permissionList_item.forEach((menu_permission: string) => {
              menu_permissionSet.add(menu_permission);
            });
            // 操作权限
            let handle_permissionList_item = item.permissionDic.handle;
            handle_permissionList_item.forEach((handle_permission: string) => {
              handle_permissionSet.add(handle_permission);
            });
          });
          return {
            menu_permissionList: Array.from(menu_permissionSet),
            handle_permissionList: Array.from(handle_permissionSet),
          };
        });

        // 更新当前登录用户信息
        let newCurrentUser = {
          ...result,
          isLogin: true,
          ifSuperAdmin,
          menu_permissionList: data.value?.menu_permissionList || [],
          handle_permissionList: data.value?.handle_permissionList || [],
        };
        currentUserStore.setCurrentUser(newCurrentUser);
        permissionStore.setPermissionsList(
          newCurrentUser.handle_permissionList.map((item) => String(item))
        );

        // 跳转到首页
        navigateTo("/");
      } catch (e: any) {
        callbackMessage.value = {
          show: true,
          valid: false,
          content: e.data.statusMessage,
        };
      }
    }
  });
};

// 其他登录方式的图标
let loginWay_list = [
  { icon: "mdi:wechat", color: "#07cd66" },
  { icon: "flat-color-icons:phone-android" },
  { icon: "icon-park:tencent-qq" },
];

const queryAccount = (queryString: string, cb: (arg0: any) => void) => {
  let accountList_temp = accountList.map((item: string) => {
    return {
      value: item,
    };
  });
  var results = queryString
    ? accountList_temp.filter(createFilter(queryString))
    : accountList_temp;
  cb(results);
};

const createFilter = (queryString: string) => {
  return (item: { value: string }) => {
    return item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};

const chooseAccount = async (newAccount: Record<string, any>) => {
  if (accountList.includes(newAccount.value)) {
    formData.remember = true;
  }
  await nextTick();
  ref_form.value?.clearValidate();
};
</script>
<template>
  <div class="flex">
    <div class="w-screen h-screen lt-md:position-absolute! z--1 left-0 top-0">
      <img
        class="w-full h-full object-cover object-position-56-50"
        src="https://p7.itc.cn/q_70/images03/20210827/334d703278da4df0822326f7d31c9eed.jpeg"
      />
    </div>
    <div class="flex items-center justify-center w-full h-screen">
      <!-- 登录表单 -->
      <div class="max-w-360px bg-white p-10 lt-md:rounded lt-md:shadow">
        <div class="text-28px font-bold text-center p-6">
          {{ appConfig.title }}
        </div>
        <el-form :model="formData" ref="ref_form">
          <el-form-item
            prop="account"
            :rules="[
              { required: true, message: '请输入账号', trigger: 'blur' },
            ]"
          >
            <el-autocomplete
              clearable
              class="inputStyle"
              v-model="formData.account"
              :fetch-suggestions="queryAccount"
              placeholder="请输入账号"
              @select="chooseAccount"
            >
              <template #prefix>
                <Icon name="mdi:account" />
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item
            prop="password"
            :rules="[
              { required: true, message: '请输入密码', trigger: 'blur' },
            ]"
          >
            <el-input
              show-password
              clearable
              type="password"
              v-model="formData.password"
              placeholder="请输入密码"
            >
              <template #prefix>
                <Icon name="wpf:password1" />
              </template>
            </el-input>
          </el-form-item>
          <div class="flex justify-between items-center">
            <div>
              <el-checkbox
                v-model="formData.remember"
                label="记住账号"
                size="large"
              />
            </div>
            <div>
              <el-link
                type="primary"
                :underline="false"
                @click="
                  ElNotification({
                    message: appConfig.adminTip,
                    type: 'warning',
                  })
                "
                >忘记密码</el-link
              >
              <el-text type="primary"> / </el-text>
              <el-link type="primary" :underline="false" href="/user/signUp"
                >注册</el-link
              >
            </div>
          </div>
          <S-msg :msg="callbackMessage" />
          <el-form-item>
            <el-button type="primary" class="w-full" @click="login(ref_form)"
              >登录</el-button
            >
          </el-form-item>
        </el-form>
        <el-divider>
          <span class="text-10px">其他登录方式</span>
        </el-divider>
        <div class="flex justify-around">
          <Icon
            v-for="(item, index) in loginWay_list"
            :key="index"
            :name="item.icon"
            :style="{
              color: item.color,
            }"
            class="inline-block text-24px cursor-pointer"
            @click="
              ElNotification({
                message: appConfig.adminTip,
                type: 'warning',
              })
            "
          />
        </div>
      </div>
    </div>
  </div>
</template>
